import os
import platform
import shutil
import sys
import tempfile
from datetime import timedelta


def get_app_support_directory():

    os_type = platform.system().lower()
    if os_type == "darwin":
        app_support_dir = os.path.expanduser("~/Library/Application Support")
        config_dir = os.path.join(app_support_dir, "subtitle_agent")
    elif os_type == "windows":
        app_data_dir = os.getenv("APPDATA")
        config_dir = os.path.join(app_data_dir, "subtitle_agent")
    else:
        config_dir = os.path.join(get_base_dir(), "config")
    if not os.path.exists(config_dir):
        os.makedirs(config_dir)
    return config_dir


def get_temp_path():
    temp_dir = tempfile.gettempdir()
    subtitle_agent_dir = os.path.join(temp_dir, "subtitle_agent")
    if not os.path.exists(subtitle_agent_dir):
        os.makedirs(subtitle_agent_dir)
    return subtitle_agent_dir


def get_audio_temp_dir():
    audio_temp_dir = os.path.join(get_temp_path(), "audio")
    if not os.path.exists(audio_temp_dir):
        os.makedirs(audio_temp_dir)
    return audio_temp_dir


def clear_audio_temp_dir():
    audio_temp_dir = get_audio_temp_dir()
    if os.path.exists(audio_temp_dir):
        shutil.rmtree(audio_temp_dir)


def get_base_dir():
    base_dir = os.path.dirname(__file__)
    return base_dir


def frame_to_timecode(frame, fps):
    """
    将帧数转换为时间码
    :param frame: 帧数
    :param fps: 帧率
    :return: 时间码
    """
    frames = int(frame % fps)
    hours = int(frame // (fps * 60 * 60))
    minutes = int((frame // (fps * 60)) % 60)
    seconds = int((frame // fps) % 60)
    return f"{hours:02d}:{minutes:02d}:{seconds:02d}:{frames:02d}"


def timecode_to_frame(timecode, fps):
    """将时间码转换为帧数"""
    hours, minutes, seconds, frames = timecode.split(":")
    return int(hours) * fps * 60 * 60 + int(minutes) * fps * 60 + int(seconds) * fps + int(frames)


def convert_time(seconds):
    """将秒数转换为 SRT 时间格式"""
    td = timedelta(seconds=seconds)
    hours = td.seconds // 3600
    minutes = (td.seconds // 60) % 60
    seconds = td.seconds % 60
    milliseconds = td.microseconds // 1000
    return f"{hours:02d}:{minutes:02d}:{seconds:02d},{milliseconds:03d}"


def get_ffmpeg_path():
    """获取 ffmpeg 路径"""
    if getattr(sys, "frozen", False):
        # 如果是打包后的应用
        if sys.platform == "darwin":
            # macOS
            base_path = os.path.dirname(
                os.path.dirname(os.path.dirname(sys.executable))
            )
            ffmpeg_path = os.path.join(base_path, "Contents", "MacOS", "ffmpeg")
        else:
            # Windows
            ffmpeg_path = os.path.join(os.path.dirname(sys.executable), "ffmpeg.exe")
    else:
        # 开发环境
        ffmpeg_path = "/usr/local/bin/ffmpeg"
    return ffmpeg_path
